﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

namespace AIClient.Utils
{
    public class ObjectPool<T>
    {
        private readonly ConcurrentBag<T> _objects;
        private readonly Func<T>          _objectGenerator;

        public ObjectPool(Func<T> objectGenerator)
        {
            _objects         = new ConcurrentBag<T>();
            _objectGenerator = objectGenerator;
        }

        public T Get()
        {
            return _objects.TryTake(out var item) ? item : _objectGenerator();
        }

        public void Put(T item)
        {
            _objects.Add(item);
        }

        public void Clear()
        {
            _objects.Clear();

        }
    }
}